package net.zdsoft.wpchat.support.entity;

import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 用户模块
 *
 * @author xuan
 */
public class UserModule {
    private static Logger logger = LoggerFactory.getLogger(UserModule.class);

    private static final String DEFAULT = "default";

    private AuthModule module = null;
    private UserCatalog userCatalog = null;
    private final HashMap<String, UserOperation> userOperationMap = new HashMap<String, UserOperation>();
    private final HashMap<String, UserOperation> userOperationMapKeyByName = new HashMap<String, UserOperation>();

    public UserModule(AuthModule module) {
        this.module = module;
    }

    public AuthModule getModule() {
        return module;
    }

    public UserCatalog getUserCatalog() {
        return userCatalog;
    }

    public void setUserCatalog(UserCatalog userCatalog) {
        this.userCatalog = userCatalog;
    }

    public UserOperation putUserOperation(UserOperation userOperation) {
        String operationId = userOperation.getOperation().getId();

        UserOperation _userOperation = userOperationMap.get(operationId);

        if (_userOperation == null) {
            logger.debug("Put operation[" + userOperation.getOperation().getName() + "]");

            userOperation.setUserModule(this);

            userOperationMap.put(operationId, userOperation);
            userOperationMapKeyByName.put(userOperation.getOperation().getName(), userOperation);

            return userOperation;
        }
        else {
            if (userOperation.isPermissionAll() && !_userOperation.isPermissionAll()) {

                logger.debug("replace operation[" + userOperation.getOperation().getName() + "] Permission:"
                        + _userOperation.getPermission() + " to " + userOperation.getPermission());

                userOperation.setUserModule(this);

                userOperationMap.put(operationId, userOperation);
                userOperationMapKeyByName.put(userOperation.getOperation().getName(), userOperation);

                return userOperation;
            }
        }

        return _userOperation;
    }

    public UserOperation getUserOperation(String operationName) {
        return userOperationMapKeyByName.get(operationName);
    }

    public UserOperation getDefaultUserOperation() {
        return getUserOperation(DEFAULT);
    }

}
